<template>
  <div class="pop-dialog-container">
    <div class="pop-dialog-main">
      <el-form label-position="right" :model="positionForm" :label-width="formLabelWidth" ref="positionFormRef" :rules="rules">
        <el-row>
          <el-col :span="11">
            <el-form-item label="企业名称" prop="enterpriseName">
              <el-input v-model="positionForm.enterpriseName" placeholder="请选择企业名称" readonly="readonly">
                <template #suffix>
                  <el-icon @click="findEnterprise"><Search/></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="岗位名称" prop="positionName">
              <el-input v-model="positionForm.positionName" placeholder="请输入岗位名称" maxlength="64"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="22">
            <el-form-item label="岗位职责" prop="responsibilities">
              <el-input v-model="positionForm.responsibilities" placeholder="请输入岗位职责" type="textarea" :rows="3" maxlength="65535"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="pop-dialog-footer">
      <el-row>
        <el-col :span="11" :offset="6">
          <div class="form-button-container">
            <el-button type="primary" @click="onSave">保存</el-button>
            <el-button @click="onReset">重置</el-button>
            <el-button type="primary" @click="onBack">关闭</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <el-dialog v-model="enterpriseSelectorVisible" v-if="enterpriseSelectorVisible" title="企业信息选择器(双击行选中)" :top="dialogTop" :width="dialogWidth">
      <enterprise-selector @enterprise-selected-event="handleEnterpriseSelectedEvent">
      </enterprise-selector>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {defineEmits, defineProps, inject, onMounted, reactive, ref, toRefs} from 'vue';
import positionApi from '@/api/positionApi'
import type {FormInstance} from 'element-plus';
import {ElMessage} from 'element-plus'
import type {PositionForm} from "@/types/req/positionForm";
import type {Result} from '@/types/result'
import type {Position} from "@/types/resp/position";
import type {Id} from "@/types/id";
import { Search } from '@element-plus/icons-vue';
import EnterpriseSelector from "@/views/enterprise/EnterpriseSelector.vue";

const props = defineProps<Id>()
const positionFormRef = ref<FormInstance | null>(null);
const positionForm = reactive<PositionForm>({
  enterpriseId: 0,
  enterpriseName: '',
  positionName: '',
  responsibilities: '',
})
const enterpriseSelectorVisible = ref<boolean>(false)
const emit = defineEmits<{
  (e: 'resetPositionAddEvent'): void;
  (e: 'closePositionAddEvent', data?: { search: boolean }): void;
}>()

const rules = reactive({
  enterpriseName: [
    { required: true, message: '请输入企业名称', trigger: 'blur' }
  ],
  positionName: [
    { required: true, message: '请输入岗位名称', trigger: 'blur' }
  ],
});
const dialogTop = ref<string>('')
const dialogWidth = ref<string>('')
const formLabelWidth = ref<string>('')

onMounted(() => {
  if (props.id) {
    initPositionFormById(props.id)
  }
  const globalState = inject('globalState', {} as { dialogWidth?: string, dialogTop?: string, formLabelWidth?: string })
  if (!globalState) {
    throw new Error('globalState is not provided');
  }
  const globalStateRefs = toRefs(globalState)
  if (globalStateRefs.formLabelWidth) {
    formLabelWidth.value = globalStateRefs.formLabelWidth.value || ''
  }
  if (globalStateRefs.dialogWidth) {
    dialogWidth.value = globalStateRefs.dialogWidth.value || ''
  }
  if (globalStateRefs.dialogTop) {
    dialogTop.value = globalStateRefs.dialogTop.value || ''
  }
});

const initPositionFormById = async (id: number) => {
  const resp: Result<Position> = await positionApi.findById(id)
  if (resp && resp.code === 1 && resp.data) {
    Object.assign(positionForm, resp.data)
  }
}

const onReset = () => {
  if (positionFormRef.value) {
    positionFormRef.value.resetFields()
  }
  emit('resetPositionAddEvent')
}

const onSave = () => {
  if (!positionFormRef.value) {
    return
  }
  positionFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      const resp: Result<void> = await positionApi.save(positionForm)
      if (resp && resp.code === 1) {
        ElMessage.success('保存成功')
        emit('closePositionAddEvent', {search: true})
      } else {
        ElMessage.error('保存失败:' + (resp.msg ? resp.msg : ''))
      }
    }
  })
}

const findEnterprise = () => {
  enterpriseSelectorVisible.value = true
}

const handleEnterpriseSelectedEvent = (selectedEnterprise: any) => {
  enterpriseSelectorVisible.value = false
  if (selectedEnterprise && 'enterpriseId' in selectedEnterprise && positionForm.enterpriseId !== selectedEnterprise['enterpriseId']) {
    positionForm.enterpriseId = selectedEnterprise['enterpriseId']
    positionForm.enterpriseName = selectedEnterprise['enterpriseName']
  }
}

const onBack = () => {
  emit('closePositionAddEvent')
}
</script>

<style lang="scss">
</style>
